package com.ruoyi.expressdelivery.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.expressdelivery.domain.ExpressDelivery;
import com.ruoyi.expressdelivery.mapper.ExpreeDeliveryMapper;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.expressdelivery.utils.CallExpressServiceTools;
import com.ruoyi.expressdelivery.utils.ExpressServiceCodeEnum;
import com.ruoyi.expressdelivery.utils.HttpClientUtil;
import com.ruoyi.expressdelivery.utils.IServiceCodeStandard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ExpressDeliveryServiceImpl implements ExpressDeliveryService {

    @Autowired
    ExpreeDeliveryMapper expreeDeliveryMapper;


    @Override
    public Map<String, Object> PrintSheet(String msgData) throws UnsupportedEncodingException {

        //此处替换为您在丰桥平台获取的顾客编码
        String CLIENT_CODE = "Y73UO5YO";
        // 校验码 uWXgOhGKst3G5Kurg8QqCXMCq9t0Wcyc // 沙箱环境 FOmg0ijVxDc9Bvt3pC9nQrtNat97A8d2
        String CHECK_WORD = "uWXgOhGKst3G5Kurg8QqCXMCq9t0Wcyc";
        // 请求地址; 生产环境:https://bspgw.sf-express.com/std/service, 沙箱环境:https://sfapi-sbox.sf-express.com/std/service
        String CALL_URL_BOX = "https://bspgw.sf-express.com/std/service";

        Map<String, Object> resMap = new HashMap<>();
        try {
            IServiceCodeStandard standardService = ExpressServiceCodeEnum.COM_RECE_CLOUD_PRINT_WAYBILLS;//面单打印
            CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
            // set common header
            Map<String, String> params = new HashMap<String, String>();
            String timeStamp = String.valueOf(System.currentTimeMillis());
            params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
            params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
            params.put("serviceCode", standardService.getCode());// 接口服务码
            params.put("timestamp", timeStamp);
            params.put("msgData", msgData);
            params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));

            printLog("调用打印面单实际请求：" + params);
            String a = HttpClientUtil.post(CALL_URL_BOX, params);
            JSONObject result = JSON.parseObject(a);
            printLog("打印面单结果" + result);
            String url = "";
            String token = "";
            if (result.get("apiResultCode").equals("A1000")) {
                JSONObject apiResultData = result.getJSONObject("apiResultData");
                JSONObject obj = apiResultData.getJSONObject("obj");
                if (obj != null && !obj.isEmpty()) {
                    JSONArray files = obj.getJSONArray("files");
                    for (int i = 0; i < files.size(); i++) {
                        JSONObject f = files.getJSONObject(i);
                        url = f.getString("url");
                        token = f.getString("token");
                    }
                    resMap.put("code", 200);
                }
            } else {
                resMap.put("code", 108);
            }

            resMap.put("url", url);
            resMap.put("token", token);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;
    }

    @Override
    public void insertwl(String phone, String shdz, String fname, String saleordernum, String remarks, Long companyId, String createtime, String loginname) {
        expreeDeliveryMapper.insertwl(phone, shdz, fname, saleordernum, remarks, companyId, createtime, loginname);
    }

    @Override
    public void updateWl(String phone, String shdz, String fname, String saleordernum, String remarks) {
        expreeDeliveryMapper.updateWl(phone, shdz, fname, saleordernum, remarks);
    }

    @Override
    public void updateWlfp(String phone, String shdz, String fname, String saleordernum, String remarks) {
        expreeDeliveryMapper.updateWlfp(phone, shdz, fname, saleordernum, remarks);
    }

    @Override
    @Transactional
    public Map<String, Object> placeOrderfp(String msgData, String saleorderNum, String recipients, String sender) throws UnsupportedEncodingException {
        ExpressDelivery expressDelivery1 = new ExpressDelivery();

        String CLIENT_CODE = "LJT6SBSVJH";  //此处替换为您在丰桥平台获取的顾客编码

        //String CHECK_WORD = "BP5YZ1sauRJn2rvHWE4wMXrJneT2Vs2l";//测试校验码

        String CHECK_WORD = "Aa6Worn46DP56AbdTGPgHMdf6RPw2EXM";//生产校验码

        //   String CALL_URL_BOX = "https://sfapi-sbox.sf-express.com/std/service";//测试地址

        String CALL_URL_BOX = "https://bspgw.sf-express.com/std/service";//生产环境
        Map<String, Object> resMap = new HashMap<>();
        try {
            expressDelivery1.setPhone(recipients);
            expressDelivery1.setPhone1(sender);
            CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
            IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_CREATE_ORDER;//下订单接口

            String timeStamp = String.valueOf(System.currentTimeMillis());
            Map<String, String> params = new HashMap<String, String>();

            params.put("partnerID", CLIENT_CODE);  // 顾客编码，对应丰桥上获取的clientCode
            params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
            params.put("serviceCode", standardService.getCode());// 接口服务码
            params.put("timestamp", timeStamp);
            params.put("msgData", msgData);
            params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));

            long startTime = System.currentTimeMillis();

            //  System.out.println("====调用请求：" + params.get("msgData"));
            System.out.println("调用下单实际请求：" + params);

            String result = HttpClientUtil.post(CALL_URL_BOX, params);

            // System.out.println("====调用丰桥的接口服务代码：" + String.valueOf(standardService.getCode()) + " 接口耗时：" + String.valueOf(System.currentTimeMillis() - startTime) + "====");
            System.out.println("下单接口返回结果：" + result);

            JSONObject a = JSONObject.parseObject(result);
            String apiResultCode = a.getString("apiResultCode");

            JSONObject apiResultData = a.getJSONObject("apiResultData");

            if (apiResultCode.equals("A1000") && apiResultData.get("errorCode").equals("S0000")) {
                JSONObject msgData1 = apiResultData.getJSONObject("msgData");
                JSONArray waybillNoInfoList = msgData1.getJSONArray("waybillNoInfoList");
                JSONArray routeLabelInfo = msgData1.getJSONArray("routeLabelInfo");
                for (int i = 0; i < routeLabelInfo.size(); i++) {
                    JSONObject d = routeLabelInfo.getJSONObject(i);
                    JSONObject routeLabelData = d.getJSONObject("routeLabelData");
                    String twoDimensionCode = routeLabelData.get("twoDimensionCode").toString();
                    expressDelivery1.setTwoDimensionCode(twoDimensionCode);
                }
                List<ExpressDelivery> list = waybillNoInfoList.toJavaList(ExpressDelivery.class);
                for (ExpressDelivery expressDelivery : list) {
                    expressDelivery1.setWaybillNo(expressDelivery.getWaybillNo());
                }
                expressDelivery1.setSalesInvoiceNum(saleorderNum);
                expreeDeliveryMapper.insertfpsf(expressDelivery1);
                resMap.put("code", "0");

            } else {
                System.out.println("下单失败,请查看具体原因");
                resMap.put("code", "-1");

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;

    }

    @Override
    @Transactional
    public Map<String, Object> placeOrder(String msgData, String saleorderNum, String recipients, String sender) throws UnsupportedEncodingException {

        //此处替换为您在丰桥平台获取的顾客编码
        String CLIENT_CODE = "Y73UO5YO";
        // 校验码 uWXgOhGKst3G5Kurg8QqCXMCq9t0Wcyc // 沙箱环境 FOmg0ijVxDc9Bvt3pC9nQrtNat97A8d2
        String CHECK_WORD = "uWXgOhGKst3G5Kurg8QqCXMCq9t0Wcyc";
        // 请求地址; 生产环境:https://bspgw.sf-express.com/std/service, 沙箱环境:https://sfapi-sbox.sf-express.com/std/service
        String CALL_URL_BOX = "https://bspgw.sf-express.com/std/service";

        ExpressDelivery expressDelivery1 = new ExpressDelivery();
        Map<String, Object> resMap = new HashMap<>();
        try {
            expressDelivery1.setPhone(recipients);
            expressDelivery1.setPhone1(sender);
            CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
            IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_CREATE_ORDER;//下订单接口

            String timeStamp = String.valueOf(System.currentTimeMillis());
            Map<String, String> params = new HashMap<String, String>();

            params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
            params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
            params.put("serviceCode", standardService.getCode());// 接口服务码
            params.put("timestamp", timeStamp);
            params.put("msgData", msgData);
            params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));

            long startTime = System.currentTimeMillis();

            //  System.out.println("====调用请求：" + params.get("msgData"));

            printLog("调用下单实际请求：" + params);

            String result = HttpClientUtil.post(CALL_URL_BOX, params);

            // System.out.println("====调用丰桥的接口服务代码：" + String.valueOf(standardService.getCode()) + " 接口耗时：" + String.valueOf(System.currentTimeMillis() - startTime) + "====");
            printLog("调用下单的结果" + result);
            JSONObject a = JSONObject.parseObject(result);
            String apiResultCode = a.getString("apiResultCode");

            JSONObject apiResultData = a.getJSONObject("apiResultData");

            if (apiResultCode.equals("A1000") && apiResultData.get("errorCode").equals("S0000")) {
                JSONObject msgData1 = apiResultData.getJSONObject("msgData");
                JSONArray waybillNoInfoList = msgData1.getJSONArray("waybillNoInfoList");
                JSONArray routeLabelInfo = msgData1.getJSONArray("routeLabelInfo");
                for (int i = 0; i < routeLabelInfo.size(); i++) {
                    JSONObject d = routeLabelInfo.getJSONObject(i);
                    JSONObject routeLabelData = d.getJSONObject("routeLabelData");
                    String twoDimensionCode = routeLabelData.get("twoDimensionCode").toString();
                    expressDelivery1.setTwoDimensionCode(twoDimensionCode);

                }

                List<ExpressDelivery> list = waybillNoInfoList.toJavaList(ExpressDelivery.class);
                for (ExpressDelivery expressDelivery : list) {
                    expressDelivery1.setWaybillNo(expressDelivery.getWaybillNo());

                }
                expressDelivery1.setSaleorderNum(saleorderNum);
                expreeDeliveryMapper.insertSf(expressDelivery1);
                resMap.put("code", 200);

                // 同步订单下单状态
            } else {
                resMap.put("code", "500");
                resMap.put("msg", "下单失败 - " + apiResultData.get("errorMsg"));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap;

    }

    @Override
    public Map<String, Object> placeOrderResult(String msgData) throws UnsupportedEncodingException {

        IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_SEARCH_ORDER_RESP;//下订单查询下订单是否成功
        String CALL_URL_BOX = "https://sfapi-sbox.sf-express.com/std/service";//测试校验码

        Map<String, Object> resMap = new HashMap<>();
        String CLIENT_CODE = "LJTDMI8PUE";  //此处替换为您在丰桥平台获取的顾客编码
        String CHECK_WORD = "ThbsndrbMWDEOAU1RBRyiekL8ozF8LuV";//此处替换为您在丰桥平台获取的校验码
        try {
            CallExpressServiceTools tools = CallExpressServiceTools.getInstance();

            String timeStamp = String.valueOf(System.currentTimeMillis());
            Map<String, String> params = new HashMap<String, String>();

            params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
            params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
            params.put("serviceCode", standardService.getCode());// 接口服务码
            params.put("timestamp", timeStamp);
            params.put("msgData", msgData);
            params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));

            long startTime = System.currentTimeMillis();

            //  System.out.println("====调用请求：" + params.get("msgData"));
            System.out.println("====调用实际请求：" + params);
            String result = HttpClientUtil.post(CALL_URL_BOX, params);

            System.out.println("====调用丰桥的接口服务代码：" + String.valueOf(standardService.getCode()) + " 接口耗时：" + String.valueOf(System.currentTimeMillis() - startTime) + "====");
            System.out.println("===查询下单结果接口是否成功返回结果：" + result);
            resMap.put("result", result);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;
    }

    @Override
    public Map<String, Object> selectOrder(String msgData) throws UnsupportedEncodingException {
        Map<String, Object> resMap = new HashMap<>();
        IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_SEARCH_ROUTES;//查询快递路由接口

        //  String CALL_URL_BOX = "https://sfapi-sbox.sf-express.com/std/service";//测试地址
        String CALL_URL_BOX = "https://bspgw.sf-express.com/std/service";//生产环境

        String CLIENT_CODE = "LJT6SBSVJH";  //此处替换为您在丰桥平台获取的顾客编码
        //String CHECK_WORD = "BP5YZ1sauRJn2rvHWE4wMXrJneT2Vs2l";//测试校验码
        String CHECK_WORD = "Aa6Worn46DP56AbdTGPgHMdf6RPw2EXM";//生产校验码
        try {

            CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
            String timeStamp = String.valueOf(System.currentTimeMillis());
            Map<String, String> params = new HashMap<String, String>();

            params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
            params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
            params.put("serviceCode", standardService.getCode());// 接口服务码
            params.put("timestamp", timeStamp);
            params.put("msgData", msgData);
            params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));

            long startTime = System.currentTimeMillis();

            //  System.out.println("====调用请求：" + params.get("msgData"));
            System.out.println("====调用查询快递路由实际请求：" + params);
            String result = HttpClientUtil.post(CALL_URL_BOX, params);

            JSONObject a = JSONObject.parseObject(result);
            //System.out.println("====调用丰桥的接口服务代码：" + String.valueOf(standardService.getCode()) + " 接口耗时："+ String.valueOf(System.currentTimeMillis()-startTime)+"====");
            System.out.println("===查询快递物流信息返回结果：" + result);
            String apiResultCode = a.getString("apiResultCode");
            JSONArray array = new JSONArray();
            JSONObject apiResultData = a.getJSONObject("apiResultData");
            if (apiResultCode.equals("A1000") && apiResultData.get("errorCode").equals("S0000")) {
                JSONObject msgData1 = apiResultData.getJSONObject("msgData");
                JSONArray routeResps = msgData1.getJSONArray("routeResps");

                for (int i = 0; i < routeResps.size(); i++) {
                    JSONObject routes = routeResps.getJSONObject(i);
                    array = routes.getJSONArray("routes");
                }
                resMap.put("result", array);
                resMap.put("code", 200);
            } else {
                resMap.put("code", 108);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;
    }

    @Override
    public List<ExpressDelivery> selectInformation(String saleordernum) {

        List<ExpressDelivery> list = expreeDeliveryMapper.selectInformation(saleordernum);
        return list;
    }

    @Override
    public ExpressDelivery selectExpressDelivery(String saleordernum) {

        ExpressDelivery list = expreeDeliveryMapper.selectExpressDelivery(saleordernum);
        return list;
    }

    @Override
    public Map<String, Object> selectMoney(String msgData) throws UnsupportedEncodingException {
        Map<String, Object> resMap = new HashMap<>();

        IServiceCodeStandard standardService = ExpressServiceCodeEnum.EXP_RECE_QUERY_SFWAYBILL;//下订单查询下订单是否成功
        String CALL_URL_BOX = "https://sfapi-sbox.sf-express.com/std/service";//测试地址

        String CLIENT_CODE = "LJTMOIR1Z5";  //此处替换为您在丰桥平台获取的顾客编码
        String CHECK_WORD = "5H8RFwhPylMSLOfPqC8reaKToMa5PFmr";//此处替换为您在丰桥平台获取的校验码
        try {
            CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
            String timeStamp = String.valueOf(System.currentTimeMillis());
            Map<String, String> params = new HashMap<String, String>();

            params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
            params.put("requestID", UUID.randomUUID().toString().replace("-", ""));
            params.put("serviceCode", standardService.getCode());// 接口服务码
            params.put("timestamp", timeStamp);
            params.put("msgData", msgData);
            params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));

            long startTime = System.currentTimeMillis();

            //  System.out.println("====调用请求：" + params.get("msgData"));
            System.out.println("====调用实际请求：" + params);
            String result = HttpClientUtil.post(CALL_URL_BOX, params);
            //System.out.println("====调用丰桥的接口服务代码：" + String.valueOf(standardService.getCode()) + " 接口耗时："+ String.valueOf(System.currentTimeMillis()-startTime)+"====");
            System.out.println("===查询快递运费返回结果：" + result);
            resMap.put("result", result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resMap;
    }


    @Override
    @Transactional
    public void insert(ExpressDelivery expressDelivery) {
        expreeDeliveryMapper.insertkd(expressDelivery);

    }

    @Override
    public void deleteinformation(String saleordernum) {
        expreeDeliveryMapper.deleteinformation(saleordernum);

    }

    @Override
    public List<ExpressDelivery> selectSfInformation(String saleordernum) {
        List<ExpressDelivery> list = expreeDeliveryMapper.selectSfInformation(saleordernum);
        return list;
    }

    @Override
    public List<ExpressDelivery> selectcompany(String companyid) {
        List<ExpressDelivery> list = expreeDeliveryMapper.selectcompany(companyid);
        return list;
    }

    public void printLog(Object resMap) {
        try {
            File file = new File("D:\\ruoyi\\logs\\ceshi.log");
            PrintStream printStream = new PrintStream(new FileOutputStream(file, true));
            System.setOut(printStream);
            System.out.println("这次打印的内容=====" + resMap);

            printStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}